import 'dart:async';
import 'dart:developer';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sports_new/controller/live/ali_live_logic.dart';
import 'package:sports_new/entity/match/match_live_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:url_launcher/url_launcher_string.dart';
import '../../../controller/match/detail/lq_match_detail_logic.dart';
import '../../../controller/match/detail/zq_match_detail_logic.dart';
import '../../../server/api/other_api.dart';
import '../../../utils/toast_utils.dart';
import '../../../utils/utils.dart';
import '../../../widgets/card.dart';
import '../../../widgets/share/share_sheet.dart';
import 'live_source_sheet.dart';

class AnimateLiveLogic extends GetxController{
  MatchLiveEntity? liveInfo;
  int? sportsId;
  InAppWebViewSettings setting = InAppWebViewSettings(
    useShouldOverrideUrlLoading: true,
  );
  Offset? _offset;
  bool _inLoading = true;

  bool get inLoading => _inLoading;
  set inLoading(bool value) {
    _inLoading = value;
    update();
  }

  Offset? get offset => _offset;

  set offset(Offset? value) {
    _offset = value;
    update();
  }

  Future changeLive() async{
    final liveList = await OtherApi.getVideoList(
        liveInfo?.matchId ?? 0, sportsId??1,null
    );
    final index = await LiveSourceSheet.show(
      liveList: liveList ?? [],
      select: liveInfo?.name ?? "",
      isFullScreen: MediaQuery.of(Get.context!).orientation == Orientation.landscape
    );
    if(index == null) return;
    if (liveList?[index].vformat == 'URL') {
      launchUrlString(liveList?[index].url ?? '', mode: LaunchMode.externalApplication,webViewConfiguration: const WebViewConfiguration(enableDomStorage: false));
    } else {
      if (liveList?[index].copyright == 0) {
        if(liveList?[index].url != liveInfo?.url) {
          try{
            if(sportsId == 1){
              Get.find<ZqMatchDetailLogic>(tag: "${liveInfo?.matchId}").liveInfo = liveList?[index];
            }else{
              Get.find<LqMatchDetailLogic>(tag: "${liveInfo?.matchId}").liveInfo = liveList?[index];
            }
          }catch(e){
            log("");
          }
          doRefresh(info: liveList?[index]);
        }
      } else {
        ToastUtils.show('暂无版权，请选择其他直播源');
      }
    }
    liveInfo = liveList?[index];
    update();
  }

  void doRefresh({MatchLiveEntity? info}){
    if(info?.vtype != 4) {
      var liveLogic = Get.find<AliLiveLogic>(tag: "${info?.matchId}");
      liveLogic.doRefresh(info: info);
    }
  }
}

class AnimateLiveView extends StatefulWidget {
  const AnimateLiveView({super.key, required this.liveInfo, required this.sportsId});

  final int sportsId;
  final MatchLiveEntity? liveInfo;

  @override
  State<AnimateLiveView> createState() => _AnimateLiveViewState();
}

class _AnimateLiveViewState extends State<AnimateLiveView> {
  late final AnimateLiveLogic logic;
  Timer? _hideTimer;
  bool _hideStuff = true;
  final double barHeight = 72;

  @override
  void initState() {
    logic = Get.put(
      AnimateLiveLogic(),
      tag: "${widget.liveInfo?.matchId}"
    );
    logic.liveInfo = widget.liveInfo;
    logic.sportsId = widget.sportsId;
    setState(() {});
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _hideTimer?.cancel();
  }

  void _cancelAndRestartTimer() {
    if (_hideStuff == true) {
      _startHideTimer();
    }
    setState(() {
      _hideStuff = !_hideStuff;
    });
  }

  void _startHideTimer() {
    _hideTimer?.cancel();
    _hideTimer = Timer(const Duration(seconds: 3), () {
      setState(() {
        _hideStuff = true;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AnimateLiveLogic>(
      tag: "${widget.liveInfo?.matchId}",
      builder: (logic) => SizedBox(
        width: Get.width,
        height: Get.height,
        child: Stack(
          children: [
            Positioned.fill(
              child: InAppWebView(
                initialUrlRequest: URLRequest(url: WebUri(logic.liveInfo?.url??"")),
                initialSettings: logic.setting,
                onWebViewCreated: (webController){
                  webController.loadUrl(
                    urlRequest: URLRequest(url: WebUri(logic.liveInfo?.url??""))
                  );
                },
                onReceivedHttpError: (webController, request, errorResponse){
                  Logger().d(errorResponse);
                },
                onReceivedError: (webController, request, error){
                  Logger().d(error);
                },
                onLoadStart: (webController,url){
                  logic.inLoading = true;
                },
                onLoadStop: (webController,url){
                  Future.delayed(const Duration(milliseconds: 100)).then(
                  (value) => logic.inLoading = false);
                },
                onConsoleMessage: (webController,message){
                  Logger().d(message);
                },
                gestureRecognizers:{
                  Factory<PanGestureRecognizer>(
                    () => PanGestureRecognizer()..onStart=(details){
                      Logger().d('PanGesture start');
                    }..onDown=(details){
                      Logger().d('PanGesture down');
                    }..onEnd=(details){
                      Logger().d('PanGesture end');
                    }..onCancel=(){
                      Logger().d('PanGesture cancel');
                    }..onUpdate=(details){
                      Logger().d('PanGesture update');
                    }
                  ),
              }
              )
            ),
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: _cancelAndRestartTimer,
              child: Column(
                children: [
                  _buildTopBar(context),
                  Expanded(
                    child: Container()
                  ),
                  _buildBottomBar(context)
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  AnimatedOpacity _buildTopBar(BuildContext context) {
    return AnimatedOpacity(
      opacity: _hideStuff ? 0.0 : 1,
      duration: const Duration(milliseconds: 400),
      child: Container(
        height: barHeight,
        padding: EdgeInsets.only(top: MediaQuery.of(Get.context!).orientation == Orientation.landscape?10:0, left: 10),
        decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Colours.black.withOpacity(0.8),Colors.transparent],
                begin: Alignment.topCenter,end: Alignment.bottomCenter
            )
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 40,
              child: Row(
                children: [
                  IconButton(
                    onPressed: _hideStuff?null:back,
                    icon: Image.asset(
                      Utils.getImgPath('arrow_back.png'),
                      color: Colours.white,
                      width: 24,
                      height: 24,
                    ),
                  ),
                  const Spacer(),
                  Container(width: 10),
                  if(MediaQuery.of(Get.context!).orientation == Orientation.portrait)...[
                    Block(
                      onTap: _hideStuff?null:dismiss,
                      cardStyle: const CardStyle(
                          color: Colours.transparent,
                          padding: EdgeInsets.only(right: 16)
                      ),
                      child: Image.asset(
                        Utils.getImgPath('close_live.png'),
                        color: Colours.white,
                        width: 24,
                        height: 24,
                      ),
                    ),
                    Block(
                      onTap: _hideStuff?null:() async{
                        Get.bottomSheet(
                            const ShareSheet(),
                            settings: RouteSettings(
                                arguments: ShareEntity(
                                  title: "【直播】这个专家超厉害，快来围观TA的直播",
                                  content: "免费比赛分析，尽在球客岛App",
                                )
                            )
                        );
                      },
                      cardStyle: const CardStyle(
                          color: Colours.transparent,
                          padding: EdgeInsets.only(right: 16)
                      ),
                      child: Image.asset(
                        Utils.getImgPath("live_share.png"),
                        color: Colours.white,
                        width: 24,
                        height: 24,
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  AnimatedOpacity _buildBottomBar(BuildContext context) {
    return AnimatedOpacity(
      opacity: _hideStuff ? 0.0 : 1,
      duration: const Duration(milliseconds: 400),
      child: Container(
        height: barHeight,
        padding: EdgeInsets.only(bottom: MediaQuery.of(Get.context!).orientation == Orientation.landscape?10:0),
        decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Colours.black.withOpacity(0.8),Colors.transparent],
                begin: Alignment.bottomCenter,end: Alignment.topCenter
            )
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            SizedBox(
              height: 40,
              child: Row(
                children: <Widget>[
                  const Spacer(),
                  // const QkdText("切换直播源",
                  //   color: Colours.white
                  // ).tap(logic.changeLive),
                  GestureDetector(
                    onTap: _hideStuff?null:changeOrientation,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      child: Image.asset(
                        Utils.getImgPath('fullscreen_icon.png'),
                        // color: Colours.text,
                        width: 24,
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void dismiss(){
    if(widget.sportsId == 1) {
      try {
        Get.find<ZqMatchDetailLogic>(tag: "${widget.liveInfo?.matchId}").isPlayVideo = false;
      }catch(e) {
        log(e.toString());
      }
    }else{
      try {
        Get.find<LqMatchDetailLogic>(tag: "${widget.liveInfo?.matchId}").isPlayVideo = false;
      }catch(e) {
        log(e.toString());
      }
    }
  }

  void back() async{
    if(MediaQuery.of(Get.context!).orientation == Orientation.landscape){
      await SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitUp,DeviceOrientation.portraitDown]
      );
      await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
      await Future.delayed(
          const Duration(microseconds: 300)
      ).then((value) => Get.back());
    }else{
      Get.back();
    }
  }

  void changeOrientation() async{
    if(MediaQuery.of(Get.context!).orientation == Orientation.landscape){
      await SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp,DeviceOrientation.portraitDown]
      );
      await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
      await Future.delayed(
        const Duration(microseconds: 300)
      ).then((value) => Get.back());
    }else{
      MaterialPageRoute<AnimateLiveView> page = MaterialPageRoute(
        builder: (context){
          return AnimateLiveView(liveInfo: widget.liveInfo, sportsId: widget.sportsId);
        },
      );
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.landscapeLeft,DeviceOrientation.landscapeRight]
      );
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
      await Future.delayed(const Duration(milliseconds: 300));
      await navigator?.push(page);
    }
  }
}
